﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace Hi_Baidu.Net.MutilInstance
{
    /// <summary>
    ///     提供了程序多实例的相关操作
    /// </summary>
    public class MutilRun
    {
        /// <summary>
        ///     从基础端口开始探测指定协议的可用端口
        ///     截止到指定端口号
        /// </summary>
        /// <param name="BaseProt">基础端口号</param>
        /// <param name="EndPort">结束探测端口号</param>
        /// <param name="Protocol">协议</param> 
        /// <param name="Protocol"></param>
        /// <returns>返回-1 则代表无可用端口</returns>
        public static int DirectPort(int BaseProt, int EndPort, PROTOCOL Protocol)
        {
            Socket DirectSocket = new Socket(AddressFamily.InterNetwork, Protocol == PROTOCOL.TCP ? SocketType.Stream : SocketType.Dgram, Protocol == PROTOCOL.TCP ? ProtocolType.Tcp : ProtocolType.Udp);
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            for (int i = BaseProt; i < EndPort; i++)
            {
                IPEndPoint IEP = new IPEndPoint(ipAddress, i);
                try                
                {
                    DirectSocket.Bind(IEP);
                    DirectSocket.Close();
                    return i;
                }
                catch(Exception ex)
                {}
            }
            return -1;
        }

        /// <summary>
        ///     端口协议枚举
        /// </summary>
        public enum PROTOCOL
        {
            /// <summary>
            ///     基于TCP协议
            /// </summary>
            TCP,
            /// <summary>
            ///     基于UDP协议
            /// </summary>
            UDP
        }
    }
}
